package org.ysh.core.attachment;

import org.ysh.annotation.AdditionInfoResolver;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
@AdditionInfoResolver(extensions = {"docx"})
public class Word2007AdditionInfoResolver implements AttachmentAdditionInfoResolver {
    public static final String CUSTOM_USER = "user";
    public static final String CUSTOM_HOST = "host";
    public static final String CUSTOM_TIME = "time";

    @Override
    public void addAdditionInfo(File tmpFile, AdditionInfo additionInfo) throws Exception {
        try(InputStream is = Files.newInputStream(tmpFile.toPath()); XWPFDocument doc = new XWPFDocument(is);
            XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
            OutputStream fos = Files.newOutputStream(tmpFile.toPath())){

            PoiHelper.writeCustomInfo( extractor.getCustomProperties(),additionInfo);

            doc.write(fos);

        }
    }

    @Override
    public AdditionInfo readAdditionInfo(InputStream in) throws Exception {
        try(XWPFDocument doc = new XWPFDocument(in);XWPFWordExtractor extractor = new XWPFWordExtractor(doc)){
            return PoiHelper.readAdditionInfo(extractor.getCustomProperties());
        }
    }

    public static void main(String[] args) throws Exception {
        String wordPath = "C:\\Users\\hxs_2\\Documents\\档案数字化加工软件功能.docx";
        Word2007AdditionInfoResolver word2007AdditionInfo = new Word2007AdditionInfoResolver();
        AdditionInfo additionInfo = new AdditionInfo();
        additionInfo.setUserName("Lisssi");
        additionInfo.setTime(new Date());
        additionInfo.setHost("192.168.1.1");
        word2007AdditionInfo.addAdditionInfo(new File(wordPath),additionInfo);
        additionInfo = word2007AdditionInfo.readAdditionInfo(Files.newInputStream(Paths.get(wordPath)));
        System.out.println(additionInfo);
    }
}
